package com.ethink.gateway.filter.post;

import com.ethink.gateway.constant.GatewayConstant;
import com.ethink.gateway.filter.AbstractPostFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.ArrayList;

/**
 * @author allen
 */
@Slf4j
@Component
public class CorsResponseHeaderFilter extends AbstractPostFilter {
    @Override
    public int getOrder() {
        // 指定此过滤器位于NettyWriteResponseFilter之后
        // 即待处理完响应体后接着处理响应头
        return GatewayConstant.FILTER_ORDER_CORS_RESPONSE;
    }

    @Override
    @SuppressWarnings("serial")
    public ServerWebExchange postFilter(ServerWebExchange exchange) {
        exchange.getResponse().getHeaders().entrySet().stream()
                .filter(kv -> (kv.getValue() != null && kv.getValue().size() > 1))
                .filter(kv -> (kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)
                        || kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))
                .forEach(kv -> {
                    kv.setValue(new ArrayList<String>() {{
                        add(kv.getValue().get(0));
                    }});
                });
        return exchange;
    }
}
